package com.cheng.xbsc.service.impl;

import com.cheng.xbsc.entity.Address;
import com.cheng.xbsc.mapper.AddressMapper;
import com.cheng.xbsc.service.AddressService;
import com.cheng.xbsc.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Address findByUserIdAndStatus(Integer userId) {
        return addressMapper.findByUserIdAndStatus(userId);
    }

    @Override
    public List<Address> findByUSerId() {
        return addressMapper.findByUSerId(LoginUserUtil.getUserId());
    }

    @Transactional
    @Override
    public void save(Address address) {
        address.setUserId(LoginUserUtil.getUserId());
        //判断新增地址是否是默认地址
        if ("1".equals(address.getAddressStatus())) {
            //把原来默认地址修改成非默认
            addressMapper.updateByUserIdAndStatus(LoginUserUtil.getUserId());
        }
        addressMapper.insert(address);
    }

    @Transactional
    @Override
    public void updateStatus(Integer aId) {
        //把原来默认地址修改成非默认
        addressMapper.updateByUserIdAndStatus(LoginUserUtil.getUserId());
        addressMapper.updateStatusById(aId, LoginUserUtil.getUserId());
    }

    @Override
    public void deleteById(Integer aId) {
        addressMapper.deleteByPrimaryKey(aId);
    }
}
